#include "CommonUtils.h"
#include <QFile>
#include <QString>
#include <QWidget>
#include <QSettings>
#include <QDebug>

QPixmap CommonUtils::getRoundImage(const QPixmap & src, QPixmap & mask, QSize masksize)
{	
	if (masksize == QSize(0, 0)) {
		masksize = mask.size();
	}
	else {
		mask = mask.scaled(masksize, 
			Qt::AspectRatioMode::KeepAspectRatio, 
			Qt::TransformationMode::SmoothTransformation);
	}
	QImage resultImage(masksize, QImage::Format::Format_ARGB32_Premultiplied);

	QPainter painter(&resultImage);

	painter.setCompositionMode(QPainter::CompositionMode::CompositionMode_Source);
	painter.fillRect(resultImage.rect(), Qt::GlobalColor::transparent);

	painter.setCompositionMode(QPainter::CompositionMode::CompositionMode_SourceOver);
	painter.drawPixmap(0, 0, mask);

	painter.setCompositionMode(QPainter::CompositionMode::CompositionMode_SourceIn);
	painter.drawPixmap(0, 0, src.scaled(masksize, Qt::KeepAspectRatio, Qt::SmoothTransformation));
	painter.end();

	return QPixmap::fromImage(resultImage);
}

void CommonUtils::loadStyleSheet(QWidget * widget, const QString & sheetName)
{
	QString path(":/Resources/QSS/" + sheetName + ".css");

	QFile file(path);
	file.open(QIODevice::ReadOnly);

	if (file.isOpen()) {
		widget->setStyleSheet("");
		QString styleSheet = QLatin1String(file.readAll());

		widget->setStyleSheet(styleSheet);
	}
	file.close();
}

void CommonUtils::setDefaultSkinColor(const QColor & color)
{
	//() << "CommonUtils::setDefaultSkinColor--------";
	//() << color.red(); //() << color.green(); //() << color.blue();
	//() << "CommonUtils::setDefaultSkinColor--------";

	QSettings settings("tradeprintinfo.ini", QSettings::Format::IniFormat);
	//settings.setIniCodec(QTextCodec::codecForName("UTF-8"));

	settings.setValue("DefaultSkin/red", color.red());
	settings.setValue("DefaultSKin/green", color.green());
	settings.setValue("DefaultSKin/blue", color.blue());
}

QColor CommonUtils::getDefaultSkinColor()
{
	const QString && string = "tradeprintinfo.ini";
	if (!QFile::exists(string)) {
		setDefaultSkinColor(QColor(22,154,228));
	}

	QSettings settings(string, QSettings::Format::IniFormat);
	QColor color;
	
	color.setRed(settings.value("DefaultSKin/red").toInt());
	color.setGreen(settings.value("DefaultSKin/green").toInt());
	color.setBlue(settings.value("DefaultSKin/blue").toInt());

	//() << color.red();
	//() << color.green();
	//() << color.blue();
	return color;
}
